<template>
  <div class="people">
    <p class="detail-tip">
      基本信息<label v-if="!isStatic">（必填）</label
      ><span v-if="showView && !isStatic" @click="toggleView">编辑</span>
    </p>
    <div class="com-container" v-if="showView">
      <div class="avatar" :style="{
            background: 'url(' + userInfo.avatar_img + ') center center / cover no-repeat',
          }">
      </div>
      <p class="username">{{ userInfo.truename }}</p>
      <div class="line">
        <p class="pie">
          <span>意向工作地:</span>
          <span>{{
            userInfo.other_name ||
            (userInfo.hopecity_cn && userInfo.hopecity_cn.name)
          }}</span>
        </p>
        <p class="pie">
          <span>籍贯:</span>
          <span>{{ userInfo.oldcid_cn && userInfo.oldcid_cn.name }}</span>
        </p>
        <p class="pie">
          <span>政治面貌:</span>
          <span>{{ userInfo.politic_cn }}</span>
        </p>
        <p class="pie">
          <span>在校成绩:</span>
          <span>{{ userInfo.in_school_result_cn }}</span>
        </p>
        <p class="pie">
          <span>出生日期:</span>
          <span>{{ checkDay(userInfo.birthday_cn) }}</span>
        </p>
        <p class="pie">
          <span>手机号:</span>
          <span>{{ userInfo.phone }}</span>
        </p>
        <p class="pie">
          <span>邮箱:</span>
          <span>{{ userInfo.email }}</span>
        </p>
      </div>
      <div class="line">
        <p class="pie">
          <span>自我评价:</span>
          <span>{{ userInfo.desc }}</span>
        </p>
      </div>
    </div>
    <div class="com-form" v-else>
      <div class="upload">
        <div class="img">
          <div class="imgurl" v-if="userInfo.avatar_img" :style="{
            background: 'url(' + userInfo.avatar_img + ') center center / cover no-repeat',
          }"></div>
          <p class="seat" v-else @click="dialogVisible = true">头像</p>
        </div>
        <p class="btn" @click="dialogVisible = true">上传照片</p>
        <p class="tips">支持 5M 以内 jpg、png 格式的图片</p>
        <avatar-cropper :dialog-visible.sync="dialogVisible" @closeAvatarDialog="uploadImg1"></avatar-cropper>
      </div>
      <div class="postForm">
        <div class="form-item">
          <div class="text" required>姓名:</div>
          <div class="input">
            <input
              v-model="userInfo.truename"
              type="text"
              placeholder="请输入姓名"
            />
          </div>
        </div>
        <div class="form-item">
          <div class="text" required>性别:</div>
          <div class="label">
            <label @click="toCheck(1)">
              <span class="checkbox" v-if="userInfo.sex === 1">
                <i class="el-icon-check"></i>
              </span>
              <span class="checkbox" v-else>&nbsp;</span>
              <span class="text">男</span>
            </label>
            <label @click="toCheck(2)">
              <span class="checkbox" v-if="userInfo.sex === 2">
                <i class="el-icon-check"></i>
              </span>
              <span class="checkbox" v-else>&nbsp;</span>
              <span class="text">女</span>
            </label>
          </div>
        </div>
        <div class="form-item">
          <div class="text" required>意向工作地:</div>
          <div class="select">
            <client-only>
              <el-select
                v-model="userInfo.hopecity_cn.name"
                filterable
                placeholder="请选择意向工作地"
                @change="changeCity"
              >
                <el-option
                  v-for="item in cityList"
                  :key="'cityList_' + item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </client-only>
          </div>
        </div>
        <div class="form-item" v-if="userInfo.hopecid === 0">
          <div class="text" required>填写意向工作地:</div>
          <div class="input">
            <input
              v-model="userInfo.other_name"
              type="text"
              placeholder="请输入工作地"
            />
          </div>
        </div>
        <div class="form-item">
          <div class="text" required>籍贯:</div>
          <div class="select">
            <client-only>
              <el-select
                v-model="userInfo.oldcid_cn.name"
                filterable
                placeholder="请选择籍贯"
                @change="changeOldCity"
              >
                <el-option
                  v-for="item in provinceList"
                  :key="'oldcidList_' + item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </client-only>
          </div>
        </div>
        <div class="form-item">
          <div class="text" required>在校成绩:</div>
          <div class="select">
            <client-only>
              <el-select
                v-model="userInfo.in_school_result"
                placeholder="选择在校成绩"
                @change="changeAchieve"
              >
                <el-option
                  v-for="item in achievementList"
                  :key="'achievementList_' + item.id"
                  :label="item.tagname"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </client-only>
          </div>
        </div>
        <div class="form-item">
          <div class="text" required>政治面貌:</div>
          <div class="select">
            <client-only>
              <el-select
                v-model="userInfo.politic"
                placeholder="选择政治面貌"
                @change="changePolitic"
              >
                <el-option
                  v-for="item in politicList"
                  :key="'politicList_' + item.id"
                  :label="item.tagname"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </client-only>
          </div>
        </div>
        <div class="form-item">
          <div class="text" required>出生日期:</div>
          <div class="select small">
            <client-only>
              <el-select
                v-model="userInfo.birthday_cn.year"
                @change="toSetDayList"
                placeholder="选择年"
              >
                <el-option
                  v-for="item in yearList"
                  :key="item"
                  :value="item"
                  :label="item + '年'"
                >
                </el-option>
              </el-select>
              <el-select
                v-model="userInfo.birthday_cn.month"
                @change="toSetDayList"
                placeholder="选择月"
              >
                <el-option
                  v-for="item in monthList"
                  :key="item"
                  :value="item"
                  :label="item + '月'"
                >
                </el-option>
              </el-select>
              <el-select
                v-model="userInfo.birthday_cn.day"
                placeholder="选择日"
              >
                <el-option
                  v-for="item in dayList"
                  :key="item"
                  :value="item"
                  :label="item + '日'"
                >
                </el-option>
              </el-select>
            </client-only>
          </div>
        </div>
        <div class="form-item">
          <div class="text" required>手机号码:</div>
          <div class="input">
            <input
              v-model="userInfo.phone"
              type="text"
              placeholder="请输入手机号码"
            />
          </div>
        </div>
        <div class="form-item">
          <div class="text" required>邮箱:</div>
          <div class="input">
            <input
              v-model="userInfo.email"
              type="text"
              placeholder="请输入邮箱"
            />
          </div>
        </div>
        <div class="form-item">
          <div class="text" required>自我评价:</div>
          <div class="textarea">
            <textarea
              v-model="userInfo.desc"
              maxlength="700"
              placeholder="请输入自我评价"
            />
            <p class="count">
              你还可以输入<span>{{ textCount }}</span
              >字
            </p>
          </div>
        </div>
        <div class="submit">
          <button class="confirm" type="button" @click="submit">保存</button>
          <button class="cancel" type="button" @click="cancel">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { uploadFile, getCityProvince } from '@/api/users';
import { getYear, getMonth, getDay } from '@/utils/constant';
import avatarCropper from '@/components/avatarCropper/avatarCropper.vue';
export default {
  props: ['info', 'eduResult', 'politicResult', 'city', 'isStatic'],
  data () {
    return {
      dialogVisible: false,
      userInfo: {
        truename: '',
        email: '',
        sex: null,
        birthday_cn: {
          year: '',
          month: '',
          day: '',
        },
        politic: '',
        politic_cn: '',
        avatar_img: '',
        hopecid: '',
        oldcid: '',
        other_name: '',
        desc: '',
        in_school_result: '',
        in_school_result_cn: '',
        oldcid_cn: { name: '' },
        hopecity_cn: { name: '' },
      },
      showView: true,
      cityList: [],
      provinceList: [],
      achievementList: [],
      politicList: [
        {
          id: 105,
          tagname: '群众',
          pid: 64
        },
        {
          id: 106,
          tagname: '共青团员',
          pid: 64
        },
        {
          id: 107,
          tagname: '中共预备党员',
          pid: 64
        },
        {
          id: 108,
          tagname: '中共党员',
          pid: 64
        }
      ],
      yearList: [],
      monthList: [],
      dayList: [],
      textCount: 700
    }
  },
  watch: {
    info (val) {
      this.userInfo = val;
    },
    eduResult (val) {
      this.achievementList = val;
    },
    city (val) {
      this.cityList = val;
    },
    'userInfo.desc' (val) {
      val && (this.textCount = 700 - val.length);
    },
  },
  computed: {
    checkDay () {
      return (birth = { year: '', month: '', day: '' }) => {
        if (birth.year && birth.month && birth.day) {
          return `${birth.year}年${birth.month}月${birth.day}日`
        } else {
          return '';
        }
      }
    }
  },
  created () {
    this.userInfo = this.info;
    this.achievementList = this.eduResult;
    this.cityList = this.city;
    this.yearList = getYear();
    this.monthList = getMonth();
    this.dayList = getDay();
    !this.isStatic && this.toGetCityProvince();
  },
  mounted () {
  },
  methods: {
    toGetCityProvince () { // 获取省份
      getCityProvince({}).then(res => {
        if (res.code === 200) {
          this.provinceList = res.data;
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        console.log(err)
        this.$message.error(err || '网络错误！')
      })
    },
    changeAchieve (data) {
      this.userInfo.in_school_result = data;
      const curOne = this.achievementList.find(s => s.id === data) || {};
      this.userInfo.in_school_result_cn = curOne.tagname || '';
    },
    changePolitic (data) {
      this.userInfo.politic = data;
      const curOne = this.politicList.find(s => s.id === data) || {};
      this.userInfo.politic_cn = curOne.tagname || '';
    },
    changeCity (data) {
      data !== 0 && this.userInfo.other_name && (this.userInfo.other_name = '');
      this.userInfo.hopecid = data;
      const curOne = this.cityList.find(s => s.id === data) || {};
      this.userInfo.hopecity_cn.name = curOne.name || '';
    },
    changeOldCity (data) {
      this.userInfo.oldcid = data;
      const curOne = this.provinceList.find(s => s.id === data) || {};
      this.userInfo.oldcid_cn.name = curOne.name || '';
    },
    toSetDayList (data) {
      if (this.userInfo.birthday_cn.year && this.userInfo.birthday_cn.month) {
        this.dayList = getDay(this.userInfo.birthday_cn.year, this.userInfo.birthday_cn.month);
        // 处理各月份最大天数不同的情况 、年月改变、日跟随改变
        if (this.userInfo.birthday_cn.day) {
          const lastDay = this.dayList[this.dayList.length - 1];
          if (Number(lastDay) < Number(this.userInfo.birthday_cn.day)) {
            this.userInfo.birthday_cn.day = '';
          }
        }
      }
    },
    toggleView () {
      this.showView = false;
    },
    toCheck (type) {
      this.userInfo.sex = type;
    },
    uploadImg (e) {
      const file = e.target.files[0];
      if (!file) { return }

      // KB单位,可以获取图片的大小，到时候可以根据图片大小进行选择上传
      // const imgSize = file.size / 1024;
      // const fileType = file.type;

      const reader = new FileReader();

      reader.onloadend = data => {
        // if (/^image\[jpeg|png|gif]/.test(fileType)) {
        //   console.log(this.result);
        // }
        // 图片的 base64 格式, 可以直接当成 img 的 src 属性值
        // const dataURL = reader.result;
        // 在这里就可以进行图片地址的获取了，到时候后台上传的图片就是根据这个来的
        // that.userInfo.avatar_img = dataURL;

        const formData = new FormData();
        formData.append('file', file);
        uploadFile(formData).then(res => {
          if (res.code === 200) {
            this.userInfo.avatar_img = res.data.link;
            this.$message.success('上传成功！');
          } else {
            this.$message.error(res.msg)
          }
        })
      }
      // console.log(file);
      reader.readAsDataURL(file);
    },
    uploadImg1 (file) {
      this.dialogVisible = false;
      if (!file) { return }
      // KB单位,可以获取图片的大小，到时候可以根据图片大小进行选择上传
      // const imgSize = file.size / 1024 / 1024;
      const fileType = file.type;
      const reader = new FileReader();

      reader.onloadend = data => {
        if (/^image\[jpeg|png|gif]/.test(fileType)) {
          console.log(this.result);
        }
        const file2 = new File([file], 'logo.jpg', {type: fileType});
        // 图片的 base64 格式, 可以直接当成 img 的 src 属性值
        // const dataURL = reader.result;
        // this.comInfo.logo = dataURL;
        // this.logo = file;
        const formData = new FormData();
        formData.append('file', file2);
        uploadFile(formData).then(res => {
          if (res.code === 200) {
            this.userInfo.avatar_img = res.data.link;
            this.$message.success('上传成功！');
          } else {
            this.$message.error(res.msg)
          }
        })
      }
      // console.log(file);
      reader.readAsDataURL(file);
    },
    upload () {
      this.$refs.imgfile.click()
    },
    cancel () {
      this.showView = true;
    },
    submit () {
      this.showView = true;
      // this.$emit('setAvatar', this.$refs.imgfile.files[0] || '');
      // const uid = this.$store.state.user.authUser.id;

      // if (!uid) {
      //   this.$message.error('未获取到用ID,请重新登录！')
      //   return
      // }
      // const { truename, sex, hopecid, oldcid, phone, email, desc } = this.userInfo;
      // const birthdayCn = this.userInfo.birthday_cn;
      // // const oldcidCn = this.userInfo.oldcid_cn;
      // // const hopecityCn = this.userInfo.hopecity_cn;
      // const inSchoolResult = this.userInfo.in_school_result;
      // let objParams = {
      //   truename,
      //   sex,
      //   oldcid,
      //   hopecid,
      //   birthday: birthdayCn,
      //   in_school_result: inSchoolResult,
      //   phone,
      //   email,
      //   desc,
      // };
      // objParams = JSON.stringify(objParams);
      // const formData = new FormData();
      // formData.append('uid', uid);
      // formData.append('resume', objParams);
      // formData.append('avatar_img', this.$refs.imgfile.files[0] || '');
      // try {
      //   updateResume(formData, true).then(res => {
      //     if (res.code === 200) {
      //       this.showView = true;
      //       this.$message.success(res.msg || '保存成功！');
      //     } else {
      //       this.$message.error(res.msg || '网络错误, 稍后再试！');
      //     }
      //   }).catch(err => {
      //     console.log(err)
      //     this.$message.error(err || '网络错误, 稍后再试！');
      //   })
      // } catch (err) {
      //   console.dir(err)
      //   this.errors = err.response.data.errors
      // }
    },
  }
}
</script>
<style lang="scss" scoped>
.people {
  position: relative;
  .avatar {
    text-align: center;
    font-size: 0;
    height: 180px;
    width: 180px;
    margin: 10px auto;
    overflow: hidden;
    border: 1px solid #ebebeb;
    border-radius: 50%;
    img {
      height: 100%;
    }
  }
  .username {
    height: 35px;
    font-size: 26px;
    color: #24292f;
    text-align: center;
    margin-bottom: 30px;
  }
  .line {
    padding-left: 70px;
    line-height: 22px;
    margin-bottom: 15px;
    .pie {
      display: inline-block;
      position: relative;
      padding-left: 8px;
      margin-right: 10px;
      min-width: 80px;
      span {
        font-size: 16px;
        &:first-child {
          color: #999;
          margin-right: 5px;
        }
        &:last-child {
          color: #24292f;
        }
      }
      &::before {
        content: '';
        position: absolute;
        top: 3px;
        left: 0;
        width: 2px;
        height: 16px;
        background: $base-color;
      }
    }
  }
  .com-form {
    padding: 30px 0;
    .upload {
      float: left;
      width: 350px;
      text-align: center;
      .img {
        height: 180px;
        width: 180px;
        margin: 0 auto;
        line-height: 180px;
        border: 1px solid #ebebeb;
        background: #ebebeb;
        border-radius: 50%;
        overflow: hidden;
        position: relative;
        .imgurl {
          position: absolute;
          top: 0;
          left: 0;
          height: 100%;
          width: 100%;
        }
        .seat {
          height: 100%;
          width: 100%;
          margin: 0;
          color: #999;
          cursor: pointer;
        }
      }
      .btn {
        color: #999;
        margin-top: 10px;
        &:hover {
          color: $base-color;
          cursor: pointer;
        }
      }
      .tips {
        font-size: 12px;
        color: #999;
        margin-top: 20px;
      }
    }
    .postForm {
      padding-left: 350px;
      .form-item {
        margin-bottom: 10px;
        line-height: 40px;
        & > div {
          display: inline-block;
        }
        & > .text {
          position: relative;
          padding-left: 20px;
          min-width: 140px;
          color: #24292f;
          vertical-align: top;
          &[required] {
            &::before {
              content: '*';
              position: absolute;
              left: 0px;
              top: 0px;
              color: $base-color-danger;
            }
          }
        }
        .input {
          input {
            line-height: 28px;
            border: 1px solid #ccc;
            border-radius: 4px;
            padding: 0 10px;
            width: 230px;
            font-size: 16px;
            &:active,
            &:focus {
              border-color: $base-color;
            }
          }
        }
        .label {
          label {
            margin-right: 30px;
          }
        }
        .select {
          ::v-deep .el-input__inner {
            width: 230px;
            height: 30px;
            line-height: 30px;
            border: 1px solid #ccc;
            font-size: 16px;
            color: #24292f;
            padding-right: 10px;
            &:active,
            &:focus {
              border-color: $base-color;
            }
          }
          &.small {
            ::v-deep .el-input__inner {
              width: 103px;
              padding-right: 20px;
              margin-right: 20px;
            }
            ::v-deep .el-input__suffix {
              right: 20px;
            }
          }
        }
        .textarea {
          margin-top: 10px;
          textarea {
            resize: none;
            height: 140px;
            width: 360px;
            border: 1px solid #ccc;
            border-radius: 4px;
            padding: 10px;
            color: #24292f;
            font-size: 16px;
            &:active,
            &:focus {
              border-color: $base-color;
            }
          }
          .count {
            text-align: right;
            span {
              color: $base-color;
              margin: 0 5px;
            }
          }
        }
      }
      .submit {
        text-align: left;
      }
    }
  }
}
</style>
